import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { OrganizationService } from './organization.service';
import { OrganizationInput } from './dto/organization.input.type';
// import { Query } from '@nestjs/common';
import { OrganizationType } from './dto/organization.type';
import { GqlAuthGuard } from '@/common/guards/auth.guards';
import { UseGuards } from '@nestjs/common';
// import { Result } from '@/common/dto/result.type';
import {
  ORG_DEL_FAIL,
  ORG_FAIL,
  ORG_NOT_EXIST,
  SUCCESS,
  UPDATE_ERROR,
} from '@/common/constants/code';
import { CurUserId } from '@/common/decorators/current-user.decorator';
import { PageInput } from '@/common/dto/page.input';
import {
  OrganizationResult,
  OrganizationResults,
} from './dto/organization.output.type';
import { Result } from '@/common/dto/result.type';
import { OrgImageService } from '../orgImage/orgImage.service';
import { FindOptionsWhere, Like } from 'typeorm';
import { Organization } from './models/organization.entity';

@Resolver(() => OrganizationType)
@UseGuards(GqlAuthGuard) //启用守卫
export class OrganizationResolver {
  constructor(
    private readonly organizationService: OrganizationService,
    private readonly orgImageService: OrgImageService,
  ) {}

  @Query(() => OrganizationResult, { description: '使用ID查询用户' })
  async getOrganizationInfo(
    @Args('id') id: string,
  ): Promise<OrganizationResult> {
    // const id = cxt.req?.user?.id || '';
    const result = await this.organizationService.findById(id);
    if (result) {
      return {
        code: SUCCESS,
        data: result,
        message: '获取成功',
      };
    }
    return {
      code: ORG_NOT_EXIST,
      message: '门店信息不存在',
    };
  }
  // 将新增和修改合并到一个接口
  @Mutation(() => OrganizationResult)
  async commitOrganization(
    @Args('params') params: OrganizationInput,
    @CurUserId() userId: string,
    @Args('id', { nullable: true }) id?: string,
  ): Promise<Result> {
    if (id) {
      const organization = await this.organizationService.findById(id);
      if (!organization) {
        return {
          code: ORG_NOT_EXIST,
          message: '门店信息不存在',
        };
      }
      console.log('commitOrganization-老图片物理删除-begin', id);
      // 由于图片在更新时会将老图片的外键删去，变为僵尸图片，这里的操作是将老图片物理删除
      const delRes = await this.orgImageService.deleteByOrg(id);
      console.log('commitOrganization-老图片物理删除-end', id);
      if (!delRes) {
        return {
          code: ORG_FAIL,
          message: '图片删除失败，无法更新信息',
        };
      }
      const res = await this.organizationService.updateById(id, {
        ...params,
        updateBy: userId,
      });
      if (res) {
        return {
          code: SUCCESS,
          message: '更新成功',
        };
      }
      return {
        code: UPDATE_ERROR,
        message: '更新失败',
      };
    }
    // 如果没有，那就创建
    const res = await this.organizationService.create({
      ...params,
      createBy: userId,
    });
    if (res) {
      return {
        code: SUCCESS,
        message: '创建成功',
      };
    }
    return {
      code: ORG_FAIL,
      message: '操作失败',
    };
  }
  // 获取多个实例
  @Query(() => OrganizationResults)
  async getOrganizations(
    @Args('page') page: PageInput,
    @CurUserId() userId: string,
    @Args('name', { nullable: true }) name?: string,
  ): Promise<OrganizationResults> {
    // const id = cxt.req?.user?.id || '';
    const { pageNum, pageSize } = page;
    const where: FindOptionsWhere<Organization> = { createBy: userId };
    if (name) {
      where.name = Like(`%${name}%`);
    }
    const [results, total] = await this.organizationService.findOrganizations({
      start: (pageNum - 1) * pageSize,
      size: pageSize,
      where,
    });

    return {
      code: SUCCESS,
      data: results,
      page: {
        pageNum,
        pageSize,
        total,
      },
      message: '获取成功',
    };
  }
  // @Mutation(() => Boolean, { description: '新增' })
  // async createOrganization(
  //   @Args('params') params: OrganizationInput,
  // ): Promise<boolean> {
  //   return await this.organizationService.create(params);
  // }
  @Mutation(() => Result, { description: '删除' })
  async deleteOrganization(
    @Args('id') id: string,
    @CurUserId() userId: string,
  ): Promise<Result> {
    const result = await this.organizationService.findById(id);
    if (result) {
      const delRes = await this.organizationService.deleteById(id, userId);
      if (delRes) {
        return {
          code: SUCCESS,
          message: '删除成功',
        };
      }
      return {
        code: ORG_DEL_FAIL,
        message: '删除失败',
      };
    }
    return {
      code: ORG_NOT_EXIST,
      message: '门店不存在',
    };
  }
  //   @Query(() => OrganizationType, { description: '使用ID查询用户' })
  //   async find(@Args('id') id: string): Promise<OrganizationType> {
  //     return await this.organizationService.findById(id);
  //   }
  //   @Mutation(() => Boolean, { description: '更新用户' })
  //   async update(
  //     @Args('id') id: string,
  //     @Args('params') params: OrganizationInput,
  //   ): Promise<boolean> {
  //     return await this.organizationService.update(id, params);
  //   }
  //   @Mutation(() => Boolean, { description: '删除用户' })
  //   async del(@Args('id') id: string): Promise<boolean> {
  //     return await this.organizationService.del(id);
  //   }
}
